<?php

/**
 * 集货云仓SDK
 * @author chenyun
 */

namespace App\Service\VendorClient\Shopjihuoyun;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;
use Hyperf\Utils\WaitGroup;

class ShopjihuoyunApiClient
{
    private $account  = 'Shopjihuoyun';
    protected $config;
    protected $RouteMap = [
        'getAccessToken'        => '/api/v2/getAccessToken',
        'queryGoodsList'        => '/api/v2/getGoodsList',
        'queryGoodsDetail'      => '/api/v2/getGoodsDetail',
        'createOrder'           => '/api/v2/createOrder',
        'cancelOrder'           => '/api/v2/cancelOrders',
        'queryOrderExpress'     => '/api/v2/getExpress',
    ];
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] ) 
    {   
        ini_set('serialize_precision', 16);
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $IdCardFrontImage = "";
        $IdCardBackImage  = "";
        $apply_extends    = [];
        //商品下单组
        $skuList = [];
        foreach ($params['orderGoods'] as $key => $item ) 
        {
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //商品组
            $skuList[] = [
                "sku_id"    => $item['supplier_skucode'],
                "num"       => $quantity
            ];
        }
        if($orderInfo['apply_extends']){
            //下单支付的时候支付信息
            $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        }
        $goods_type = $params['orderGoods'][0]["goods_type"];
        if($goods_type == 2){
            //获取身份证正反面
            $IdCardFrontImage = $apply_extends['idCardFrontImage'] ?? '';
            $IdCardBackImage  = $apply_extends['idCardBackImage'] ?? '';
            $IdCardFrontImage = $order['idCardFrontImage'] ? $order['idCardFrontImage'] : $IdCardFrontImage;
            $IdCardBackImage  = $order['idCardBackImage'] ? $order['idCardBackImage'] : $IdCardBackImage;
            if (empty($IdCardFrontImage) || empty($IdCardBackImage)) {
                return Normal::returnCode(Normal::FAIL, "身份证图片正反面都需要提供！");
            }
        }
        $access_token = $this->getAccessToken();
        if($access_token["code"] != Normal::SUC){
            return $access_token;
        }
        
        //创建订单数据
        $data = [
            'access_token'  => $access_token["data"],
            'skuList'       => json_encode($skuList,JSON_UNESCAPED_UNICODE),
            'source'        => $this->config['source'],
            'mobile'        => $orderInfo['recveive_phone'],
            'name'          => $orderInfo['receive_name'],
            'order_sn'      => $orderInfo['supplier_dsn'],
            'province'      => $orderInfo['province'],
            'city'          => $orderInfo['city'],
            'district'      => $orderInfo['district'],
            'addressDetail' => $orderInfo['receive_address'],
            'idcard'        => $orderInfo['buyer_idcard'],
            'idcard_front'  => $IdCardFrontImage,
            'idcard_back'   => $IdCardBackImage,
            'remark'        => $orderInfo["order_remark"],
        ];
        
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data
        ];
        $res = $this->execute($requestParam);
        if( $res['code'] == Normal::SUC ) {
            return Normal::returnCode(Normal::SUC,"订单推送成功",[
                'thirdpart_order_sn' => $res["data"]['order_no']
            ]);
        }
        return $res;
    }
   
    /**
     * 获取取消订单
     */
    public function cancelOrder( $params = [] ) 
    {
        $orderSupplier= $params['supplierOrder'];
        $access_token = $this->getAccessToken();
        if($access_token["code"] != Normal::SUC){
            return $access_token;
        }
        $token = $access_token["data"];
        $data = [
            'access_token'    => $token,
            'source'          => $this->config["source"],
            'order_no'        => $orderSupplier["thirdpart_order_sn"],
        ];
        $requestParam = [
            'method'    => 'cancelOrder',
            'data'      => $data,
        ];
        $res = $this->execute($requestParam);
        return $res;
    }
    /**
     * 查询物流单信息
     * @param array $param
     */
    public function queryOrderExpress( $params = [] )
    {
        $access_token = $this->getAccessToken();
        if($access_token["code"] != Normal::SUC){
            return $access_token;
        }
        $token = $access_token["data"];
        $data = [
            'access_token'    => $token,
            'source'          => $this->config["source"],
            'order_no'        => $params['thirdpart_order_sn'],
        ];
        $requestParam = [
            'method'    => 'queryOrderExpress',
            'data'      => $data
        ];
        $res =  $this->execute($requestParam);
        return $res;
    }
    
    
    /**
     * 查询商品信息
     */
    public function queryGoodsList($param)
    {
        $access_token = $this->getAccessToken();
        if($access_token["code"] != Normal::SUC){
            return $access_token;
        }
        $token = $access_token["data"];
        
        //获取商品列表
        $goodsWhere = [
            'access_token'  => $token,
            'source'        => $this->config['source'],
            'page'          => $param['page']  ?? 1,
            'pageNum'       => $param['limit']  ?? 50,
        ];
        
        //指定
        if( !empty($param["category_id"]) ) 
        {
            $goodsWhere['cate'] = $param["category_id"];
        }
        
        $requestParam = [
            'method'    => 'queryGoodsList',
            'data'      => $goodsWhere,
        ];
        $res  = $this->execute($requestParam);
        if( $res["code"] != Normal::SUC){
            return $res;
        }
        
        $result_query_goods = $res["data"]["list"];
        $details = [];
        $selfSellTypeSkip = [];
        foreach ($result_query_goods as $sku)
        {
            $responseParam = $this->queryGoodsDetail($sku,$token);
            if ( $responseParam['code']== Normal::SUC && isset($responseParam['data']) && $responseParam['data'] )
            {
                //1代表保税，不捞
                $goodsList = $responseParam['data'];
                if(isset($goodsList["selfSellType"]) && $goodsList["selfSellType"]> 1 && is_array($goodsList["sku_list"]) && !empty($goodsList["sku_list"]))
                {
                    $good = [];
                    foreach ($goodsList["sku_list"] as $k=>$v){
                        $cateName = "";
                        //获取商品分类信息
                        if(isset($goodsList["categorys"]) && is_array($goodsList["categorys"]) && !empty($goodsList["categorys"])){
                            $cateList = end($goodsList["categorys"]);
                            $cateName = $cateList["name"];
                        }
                        //将多规格商品处理成一单一品
                        $good =[
                            'goodsId'       => $goodsList["skuId"],
                            'name'          => $goodsList["name"],
                            'img'           => $goodsList["img"],
                            'price'         => $goodsList["price"],
                            'brandName'     => $goodsList["brandName"],
                            'saleUnit'      => $goodsList["saleUnit"],
                            'productArea'   => $goodsList["productArea"],
                            'selfSellType'  => $goodsList["selfSellType"],
                            'source'        => isset($goodsList["source"]) ? $goodsList["source"]: $this->config["source"],
                            'introduction'  => $goodsList["introduction"],
                            'selfSellType'  => $goodsList["selfSellType"],
                            'barcode'       => $goodsList["barcode"],
                            'sku_id'        => $v["sku_id"],
                            'sku_name'      => $v["sku_name"],
                            'sku_price'     => $v["sku_price"],
                            'sku_weight'    => $v["sku_weight"],
                            'sku_quantity'  => isset($v["sku_quantity"]) ? $v["sku_quantity"] : 1,
                            'sku_stock'     => $v["sku_stock"],
                            'cateName'      => $cateName,
                        ];
                        $details[]= $good;
                    }
                } else {
                    $selfSellTypeSkip[] = 1;
                }
            }
        }
        
        if( empty($details) && !empty($selfSellTypeSkip) ) {
            return Normal::returnCode(Normal::SUC,"获取成功",[
                'data'      => [],
                'has_next'  => true
            ]);
        }
        
        if( empty($details) && empty($selfSellTypeSkip) ) {
            return Normal::returnCode(Normal::SUC,"获取成功",[
                'data'      => [],
                'has_next'  => false
            ]);
        }
        
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'data'      => $details,
            'has_next'  => true
        ]);
    }
    
    /**
     * 并发接口代码
     */
    public function queryGoodsListMore()
    {
        $wg = new WaitGroup();
        $count = count($result_query_goods);
        $wg->add($count);
        foreach ($result_query_goods as $sku)
        {
            co(function () use ($wg,$sku, & $details, & $selfSellTypeSkip,&$token)
            {
                $responseParam = $this->queryGoodsDetail($sku,$token);
                if ( $responseParam['code']== Normal::SUC && isset($responseParam['data']) && $responseParam['data'] )
                {
                    //1代表保税，不捞
                    $goodsList = $responseParam['data'];
                    if(isset($goodsList["selfSellType"]) && $goodsList["selfSellType"]> 1 && is_array($goodsList["sku_list"]) && !empty($goodsList["sku_list"]))
                    {
                        $good = [];
                        foreach ($goodsList["sku_list"] as $k=>$v){
                            $cateName = "";
                            //获取商品分类信息
                            if(isset($goodsList["categorys"]) && is_array($goodsList["categorys"]) && !empty($goodsList["categorys"])){
                                $cateList = end($goodsList["categorys"]);
                                $cateName = $cateList["name"];
                            }
                            //将多规格商品处理成一单一品
                            $good =[
                                'goodsId'       => $goodsList["skuId"],
                                'name'          => $goodsList["name"],
                                'img'           => $goodsList["img"],
                                'price'         => $goodsList["price"],
                                'brandName'     => $goodsList["brandName"],
                                'saleUnit'      => $goodsList["saleUnit"],
                                'productArea'   => $goodsList["productArea"],
                                'selfSellType'  => $goodsList["selfSellType"],
                                'source'        => isset($goodsList["source"]) ? $goodsList["source"]: $this->config["source"],
                                'introduction'  => $goodsList["introduction"],
                                'selfSellType'  => $goodsList["selfSellType"],
                                'barcode'       => $goodsList["barcode"],
                                'sku_id'        => $v["sku_id"],
                                'sku_name'      => $v["sku_name"],
                                'sku_price'     => $v["sku_price"],
                                'sku_weight'    => $v["sku_weight"],
                                'sku_quantity'  => $v["sku_quantity"],
                                'sku_stock'     => $v["sku_stock"],
                                'cateName'      => $cateName,
                            ];
                            $details[]= $good;
                        }
                    } else {
                        $selfSellTypeSkip[] = 1;
                    }
                }
                $wg->done();
            });
        }
        $wg->wait();
    }
    
    
    
    /**
     * 查询商品详情
     */
    public function queryGoodsDetail($param,$token)
    {
        //查询商品详情
        $detailsWhere = [
            'access_token'  => $token,
            'source'        => $this->config["source"],
            'skuId'         => $param["skuId"],
        ];
        $requestParam = [
            'method'    => 'queryGoodsDetail',
            'data'      => $detailsWhere,
        ];
        $responseParam = $this->execute($requestParam);
        return $responseParam;
       
    }
    /**
     * 查询token值
     * @param array $param
     */
    public function getAccessToken( $param = [] )
    {
        $data = [
            'appId'         => $this->config["appId"],
            'grant_type'    => "access_token",
            'name'          => $this->config["name"],
            'password'      => $this->config["password"],
            'timestamp'     => time()
        ];
        $data["sign"] = $this->getSign($data);
        $requestParam = [
            'method'    => 'getAccessToken',
            'data'      => $data
        ];
        $res =  $this->execute($requestParam);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        $AccessToken = $res["data"]["access_token"];
        return Normal::returnCode(Normal::SUC,"获取成功",$AccessToken);
    }
    /**
     * 加签
     * @param array $param
     */
    protected function getSign( $params = [] )
    {
        //md5(appId=test&grant_type=access_token&name=name&password=.md5(password).&timestamp=1689888220)
        $string = "";
        foreach ($params as $key =>$value){
            if($key == "password"){
                $string.= $key."=".md5($value)."&";
            }else{
                $string.= $key."=".$value."&";
            }
        }
        $string = substr($string,0,-1);
        return md5($string);
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )  
    {
        if( empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        $method = $param["method"];
        $url    =$this->config["baseurl"].$this->RouteMap[$method];
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $param['data'],
                'method'    => 'post',
                'format'    => 'form-data',
                'header'    => [],
        
            ],
        ];
        
        if( in_array($method,['queryGoodsList','queryGoodsDetail','getAccessToken']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = json_decode($res,true);
        if( isset($resHttp['code']) && $resHttp['code'] == 0 ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp["data"]);
        }
        $message = isset($resHttp['msg']) ? $resHttp['msg'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }
}